/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.grnt.buddy;

import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.grnt.buddy.BuddiesTreeControler.BuddiesCtlException;
import org.grnt.common.CommonFunc;
import org.grnt.dbcommon.ControlBean;
import static org.grnt.dbcommon.DataControler.TransOpt;

/**
 *
 * It is a ControlBean subclass for add user semantic.
 * @author sayid
 */

public final class AddUser implements ControlBean {
	final Long userId;
	final String loginName;
	final String password;
	final Long root;
	final UserBean user ;
	final BuddyBean buddy;
	final String sqlStr = "INSERT INTO gt_users"
			+ "(user_id, login_name, password, create_time, root)"
			+ "VALUES(?, '?', '?', 0, ?)";

	/**
	 *
	 * This constructure must get four fields, userId, loginName, password and root.
	 * @param userId It is an id for a user and generated by IdExtractor object.
	 * @param loginName This value is used to login into system.
	 * @param password This value is used to login into system.
	 * @param root It is an id for root group buddy of the current user.
	 */
	public AddUser(Long userId, String loginName, String password, Long root) {
		this.userId    = userId;
		this.loginName = loginName;
		this.password  = password;
		this.root      = root;
		
		user  = new UserBean();
		buddy = new BuddyBean();
		user.init(userId, loginName, password, root);
		buddy.init(root, loginName + "@root:", null, userId, null, true);
		/**
		 * "@root:" Root buddy alias form is declared in a database defintion 
		 * file users_tables.sql
		 */
	}

	final public List<String> getCommands() {
		List<String> result = new ArrayList<String>();
		String command = CommonFunc.sqlStrFormat( sqlStr
				, userId.toString()
				, loginName
				, password
				, root.toString());
		command = CommonFunc.sqlNullStr2NullVal(command);
		result.add(command);
		return result;
	}

	final public boolean doInTransaction() {
		try{
			BuddiesTreeControler.addUser(user, buddy);
			return true;
		} catch (BuddiesCtlException ex) {
			Logger.getLogger(AddUser.class.getName()).log(Level.SEVERE, null, ex);
			return false;
		}
	}

	public void doAfterTransaction(TransOpt opt) {
		if (opt == TransOpt.ROLLBACK) {
			if (user != null)
				user.kill();
		}
	}
}